﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RegexLib.Web.Models.Web;
using System.Web.Security;
using RegexLib.Web.Models.Data;

namespace RegexLib.Web.Controllers
{
	public class MemberController : Controller
	{
		/// <summary>
		/// 从母版页向登录页进行转向。为了在转向时携带源地址，所以专门写了个action。
		/// </summary>
		/// <returns></returns>
		public ActionResult LoginFromMaster()
		{
			string returnUrl = Request.UrlReferrer.ToString();
			return Redirect("/Member/Login/?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl));
		}

		/// <summary>
		/// 访问登录页。
		/// </summary>
		/// <returns></returns>
		public ActionResult Login()
		{
			if (RxMembership.IsUserLoggedIn())  // 防止重复登录
				return Redirect("/Home/");

			string returl = Request["ReturnUrl"];
			ViewData["ReturnUrl"] = string.IsNullOrEmpty(returl) ? "/Home/" : returl;
			return View();
		}

		/// <summary>
		/// 提交登录信息。
		/// </summary>
		/// <param name="userEmail"></param>
		/// <param name="userPassword"></param>
		/// <param name="rememberMe"></param>
		/// <param name="returnUrl"></param>
		/// <returns></returns>
		public ActionResult LoginSubmit(
			string userEmail,
			string userPassword,
			string rememberMe,
			string returnUrl)
		{
			try
			{
				RxIPRecorder.CheckIPPolicy(Request.UserHostAddress, RxIPRecordType.LoginFailed);
			}
			catch (RxIPPausedException)
			{
				return Json(new { IsError = true, Message = "尝试次数过多，IP已被临时限制。" });
			}
			catch (RxIPBlockedException)
			{
				return Json(new { IsError = true, Message = "您的IP地址已被屏蔽，无法登录。" });
			}

			if (string.IsNullOrEmpty(userEmail))
				return Json(new { IsError = true, Message = "请输入Email地址。" });

			if (string.IsNullOrEmpty(userPassword))
				return Json(new { IsError = true, Message = "请输入密码。" });

			if (string.IsNullOrEmpty(returnUrl))
				returnUrl = "/Home/";

			try
			{
				UserInfo user = RxMembership.TryLogin(userEmail, userPassword, Request.UserHostAddress);
				FormsAuthentication.SetAuthCookie(user.UserId.ToString(), rememberMe == "on");
				RxIPRecorder.RecordIP(Request.UserHostAddress, RxIPRecordType.MakeComment);
				return Json(new { IsError = false, Message = returnUrl });
			}
			catch (RxMemberNotExistException)
			{
				RxIPRecorder.RecordIP(Request.UserHostAddress, RxIPRecordType.LoginFailed);
				return Json(new { IsError = true, Message = "用户不存在。" });
			}
			catch (RxInvalidPasswordException)
			{
				RxIPRecorder.RecordIP(Request.UserHostAddress, RxIPRecordType.LoginFailed);
				return Json(new { IsError = true, Message = "密码错误。" });
			}
			catch
			{
				return Json(new { IsError = true, Message = "在尝试登录时发生错误，请稍后再试。" });
			}
		}

		/// <summary>
		/// 注销。
		/// </summary>
		/// <returns></returns>
		public ActionResult Logout()
		{
			FormsAuthentication.SignOut();
			string returl = Request.UrlReferrer == null ? "/Home/" : Request.UrlReferrer.ToString();
			return Redirect(returl);
		}

		/// <summary>
		/// 访问注册页。
		/// </summary>
		/// <returns></returns>
		public ActionResult Register()
		{
			return View();
		}

		/// <summary>
		/// 提交注册申请信息。
		/// </summary>
		/// <param name="userEmail"></param>
		/// <returns></returns>
		public ActionResult RegisterSubmit(string userEmail)
		{
			try
			{
				RxIPRecorder.CheckIPPolicy(Request.UserHostAddress, RxIPRecordType.Register);
			}
			catch (RxIPPausedException)
			{
				return Json(new { IsError = true, Message = "您因为注册过于频繁，IP地址已被暂时限制。" });
			}
			catch (RxIPBlockedException)
			{
				return Json(new { IsError = true, Message = "您的IP地址已被屏蔽，无法注册。" });
			}

			string rawEmail = "";
			if (userEmail == null || (rawEmail = userEmail.Trim()) == "")
				return Json(new { IsError = true, Message = "必须填写Email地址。" });

			if (!userEmail.IsEmail())
				return Json(new { IsError = true, Message = "Email地址格式不正确。" });

			try
			{
				RxMembership.ApplyUser(rawEmail, Request.UserHostAddress);
				RxIPRecorder.RecordIP(Request.UserHostAddress, RxIPRecordType.Register);
				return Json(new { IsError = false, Message = string.Format("您的邀请信已成功发送到{0}，请查收。", HttpUtility.HtmlEncode(rawEmail)) });
			}
			catch (RxMemberAlreadyExistsException)
			{
				return Json(new { IsError = true, Message = "该Email地址已被使用，请换一个。" });
			}
			catch (Exception ex)
			{
				return Json(new { IsError = true, Message = "在发送邀请信的过程中发生错误，请稍候再试。" + ex.Message });
			}
		}

		/// <summary>
		/// 通过邀请信访问注册用户信息填写页。
		/// </summary>
		/// <returns></returns>
		public ActionResult RegisterInfo()
		{
			string email = Request["m"];
			string code = Request["c"];

			if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(code))
			{
				return Redirect("/");
			}

			try
			{
				RxMembership.CheckApply(email, new Guid(code));
			}
			catch
			{
				return Redirect("/");
			}

			ViewData["UserEmail"] = email;
			return View();
		}

		/// <summary>
		/// 提交注册用户信息。
		/// </summary>
		/// <param name="userEmail"></param>
		/// <param name="userNickname"></param>
		/// <param name="userPassword"></param>
		/// <param name="userPassword2"></param>
		/// <param name="userAccessKey"></param>
		/// <returns></returns>
		public ActionResult RegisterInfoSubmit(
			string userEmail,
			string userNickname,
			string userPassword,
			string userPassword2,
			string userAccessKey)
		{
			string rawEmail = "";
			if (userEmail == null || (rawEmail = userEmail.Trim()) == "")
				return Json(new { IsError = true, Message = "没有读取到恰当的Email地址。" });

			string rawNickname = "";
			if (userNickname == null || (rawNickname = userNickname.Trim()) == "")
				return Json(new { IsError = true, Message = "必须输入昵称。" });

			if (string.IsNullOrEmpty(userPassword))
				return Json(new { IsError = true, Message = "必须输入密码。" });

			if (userPassword != userPassword2)
				return Json(new { IsError = true, Message = "两次输入的密码不一致。" });

			if (string.IsNullOrEmpty(userAccessKey))
				return Json(new { IsError = true, Message = "必须输入访问路径。" });

			if (!userAccessKey.IsAccessKey())
				return Json(new { IsError = true, Message = "访问路径的格式不正确，请只使用小写字母和数字。" });

			try
			{
				RxMembership.RegisterUser(rawNickname, rawEmail, userAccessKey, userPassword, Request.UserHostAddress);
				return Json(new { IsError = false, Message = "注册成功，请到登录页登录。" });
			}
			catch (RxAccessKeyAlreadyExistsException)
			{
				return Json(new { IsError = true, Message = "访问路径已被使用，请换一个。" });
			}
			catch
			{
				return Json(new { IsError = true, Message = "注册过程发生错误，请稍后再试。" });
			}
		}

		/// <summary>
		/// 查看个人信息。
		/// </summary>
		/// <param name="id">用户的AccessKey，为了和UrlRouting保持一致，此处保留了id这个名字。</param>
		/// <returns>Profile视图。</returns>
		public ActionResult Profile(string id)
		{
			using (RxDataContext db = new RxDataContext())
			{
				UserInfo user = db.UserInfos.FirstOrDefault(u => u.AccessKey == id);

				if (user == null)
				{
					return Redirect("/Home/");
				}

				return View(user);
			}
		}

		/// <summary>
		/// 编辑个人信息。
		/// </summary>
		/// <returns></returns>
		public ActionResult EditProfile()
		{
			UserInfo curuser = RxMembership.GetCurrentUser();

			if (curuser == null)
				return Redirect("/Home/");

			string ak = Request["id"];

			if(string.IsNullOrEmpty(ak))
				return Redirect("/Home/");

			using (RxDataContext db = new RxDataContext())
			{
				UserInfo user = db.UserInfos.FirstOrDefault(u => u.AccessKey == ak);

				if (user == null)
					return Redirect("/Home/");

				if (curuser.UserId != user.UserId)
					return Redirect("/Home/");

				return View(user);
			}
		}

		/// <summary>
		/// 提交新的个人信息。
		/// </summary>
		/// <param name="userId">用户ID。</param>
		/// <param name="userNickname">新的昵称。</param>
		/// <returns></returns>
		public ActionResult EditProfileSubmit(Guid userId, string userNickname)
		{
			UserInfo curuser = RxMembership.GetCurrentUser();

			if (curuser == null)
				return Json(new { IsError = true, Message = "必须登录才能操作。" });

			try
			{
				using (RxDataContext db = new RxDataContext())
				{
					UserInfo user = db.UserInfos.FirstOrDefault(u => u.UserId == userId);

					if (user == null)
						return Json(new { IsError = true, Message = "用户不存在。" });

					if (user.UserId != curuser.UserId)
						return Json(new { IsError = true, Message = "无权修改他人信息。" });

					string rawNickname = "";
					if (userNickname == null || (rawNickname = userNickname.Trim()) == "")
						return Json(new { IsError = true, Message = "必须输入昵称。" });

					user.Nickname = rawNickname;
					db.SubmitChanges();
					return Json(new { IsError = false, Message = RxUrl.GetMemberProfileUrl(user.AccessKey) });
				}
			}
			catch
			{
				return Json(new { IsError = true, Message = "在修改信息时发生了错误，请稍后再试。" });
			}
		}

		/// <summary>
		/// 查看修改密码申请页。
		/// </summary>
		/// <returns></returns>
		public ActionResult ChangePassword()
		{
			return View();
		}

		/// <summary>
		/// 提交修改密码申请信息。
		/// </summary>
		/// <param name="userEmail"></param>
		/// <returns></returns>
		public ActionResult ChangePasswordSubmit(string userEmail)
		{
			try
			{
				RxIPRecorder.CheckIPPolicy(Request.UserHostAddress, RxIPRecordType.ChagePassword);
			}
			catch (RxIPPausedException)
			{
				return Json(new { IsError = true, Message = "您因为找回密码过于频繁，IP地址已被暂时限制。" });
			}
			catch (RxIPBlockedException)
			{
				return Json(new { IsError = true, Message = "您的IP地址已被屏蔽，无法找回密码。" });
			}

			string rawEmail = "";
			if (userEmail == null || (rawEmail = userEmail.Trim()) == "")
				return Json(new { IsError = true, Message = "请输入Email。" });

			try
			{
				RxMembership.ApplyChangePassword(rawEmail, Request.UserHostAddress);
				RxIPRecorder.RecordIP(Request.UserHostAddress, RxIPRecordType.ChagePassword);
				return Json(new { IsError = false, Message = string.Format("您的密码修改申请已发送到{0}，请查收。", HttpUtility.HtmlEncode(rawEmail)) });
			}
			catch (ArgumentException)
			{
				return Json(new { IsError = true, Message = "Email地址格式不正确。" });
			}
			catch (RxMemberNotExistException)
			{
				return Json(new { IsError = true, Message = "指定的用户不存在。" });
			}
			catch (Exception ex)
			{
				return Json(new { IsError = true, Message = "在发送密码修改申请的过程中发生错误，请稍后再试。" + ex.Message });
			}
		}

		/// <summary>
		/// 通过密码修改申请信访问密码重置页。
		/// </summary>
		/// <returns></returns>
		public ActionResult ResetPassword()
		{
			string userId = Request["u"];
			string code = Request["c"];

			if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(code))
			{
				return Redirect("/");
			}

			try
			{
				RxMembership.CheckPasswordApply(new Guid(userId), new Guid(code));
			}
			catch
			{
				return Redirect("/");
			}

			ViewData["UserId"] = userId;
			ViewData["ApplyCode"] = code;
			return View();
		}

		/// <summary>
		/// 提交重置的密码。
		/// </summary>
		/// <param name="userId"></param>
		/// <param name="applyCode"></param>
		/// <param name="userPassword"></param>
		/// <param name="userPassword2"></param>
		/// <returns></returns>
		public ActionResult ResetPasswordSubmit(Guid userId, Guid applyCode, string userPassword, string userPassword2)
		{
			if (string.IsNullOrEmpty(userPassword))
				return Json(new { IsError = true, Message = "请输入密码。" });

			if (userPassword != userPassword2)
				return Json(new { IsError = true, Message = "两次输入的密码不一致。" });

			try
			{
				RxMembership.CheckPasswordApply(userId, applyCode);
				RxMembership.ResetPassword(userId, userPassword, Request.UserHostAddress);
				return Json(new { IsError = false, Message = "您的密码已重置，下次登录请使用新密码。" });
			}
			catch
			{
				return Json(new { IsError = true, Message = "在重置密码时发生错误，请稍后再试。" });
			}
		}
	}
}
